<template>
  <div>
    <!-- 主列表页面 -->
    <div v-if="!showEditPage && !showProcessPage">
      <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
        <a-row
          class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden"
        >
          <!-- 查询条件 -->
          <a-row v-if="showSearchRow" class="w-full">
            <a-form
              :model="searchForm"
              label-align="left"
              layout="inline"
              size="small"
            >
              <a-form-item field="purchaseApplicationCode" label="申请编号">
                <a-input
                  v-model="searchForm.purchaseApplicationCode"
                  placeholder="请输入申请编号"
                  allow-clear
                />
              </a-form-item>
              <a-form-item field="purchaseApplicationName" label="申请名称">
                <a-input
                  v-model="searchForm.purchaseApplicationName"
                  placeholder="请输入申请名称"
                  allow-clear
                />
              </a-form-item>
              <a-form-item field="purchaseApplicationStatus" label="申请状态">
                <a-select
                  v-model="searchForm.purchaseApplicationStatus"
                  placeholder="请选择申请状态"
                  allow-clear
                >
                  <a-option
                    v-for="dict in dicts[
                      proxy.DICT.lindiPurchaseApplicationStatus
                    ]"
                    :key="dict.dictKey"
                    :value="String(dict.dictKey)"
                  >
                    {{ dict.dictValue }}
                  </a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="applicationTimeStart" label="申请时间">
                <a-range-picker
                  v-model="searchForm.applicationTimeRange"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  style="width: 400px"
                />
              </a-form-item>
            </a-form>
            <a-row class="w-full mt-2" justify="center">
              <a-space>
                <a-button type="primary" @click="search">
                  <template #icon>
                    <icon-search />
                  </template>
                  <template #default>查询</template>
                </a-button>
                <a-button @click="reset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <template #default>重置</template>
                </a-button>
              </a-space>
            </a-row>
          </a-row>

          <!-- 分割线 -->
          <a-divider v-if="showSearchRow" class="mt-2" />

          <!-- 数据操作区 -->
          <a-row class="w-full flex justify-between">
            <a-space>
              <!-- 添加 -->
              <a-button
                v-perm="['lindi:purchaseApplication:add']"
                size="small"
                type="primary"
                @click="handleAdd"
              >
                <template #icon>
                  <icon-plus />
                </template>
                <template #default>新增</template>
              </a-button>
            </a-space>
            <a-space>
              <!-- 刷新 -->
              <a-button shape="circle" size="small" @click="search">
                <template #icon>
                  <icon-refresh />
                </template>
              </a-button>
              <!-- 收缩/展开 -->
              <a-button
                shape="circle"
                size="small"
                @click="showSearchRow = !showSearchRow"
              >
                <template #icon>
                  <icon-caret-up v-if="showSearchRow" />
                  <icon-caret-down v-else />
                </template>
              </a-button>
            </a-space>
          </a-row>

          <!-- 数据展示区 -->
          <a-row class="w-full flex-1 mt-3 overflow-y-auto">
            <a-table
              row-key="purchaseApplicationId"
              :loading="loading"
              :pagination="pagination"
              :columns="columns"
              :data="tableData"
              :bordered="false"
              :scroll="{ minWidth: 800, y: '100%' }"
              class="w-full"
              table-layout-fixed
              @page-change="handlePageChange"
              @page-size-change="handlePageSizeChange"
            >
            </a-table>
          </a-row>
        </a-row>
      </a-card>
    </div>

    <!-- 编辑页面 -->
    <PurchaseApplicationEditPage
      v-if="showEditPage"
      :purchase-application-id="editParams.purchaseApplicationId"
      @cancel="handleEditCancel"
      @ok="handleEditOk"
    />

    <!-- 审批流程页面 -->
    <PurchaseApplicationProcess
      v-if="showProcessPage"
      :purchase-application-id="processParams.purchaseApplicationId"
      @cancel="handleProcessCancel"
      @ok="handleProcessOk"
    />

    <!-- 详情模态窗 -->
    <a-modal
      v-model:visible="showDetailModal"
      title="购买申请详情"
      :width="1200"
      :footer="false"
      :mask-closable="false"
      @cancel="handleDetailCancel"
    >
      <PurchaseApplicationDetail
        v-if="showDetailModal"
        :params="detailParams"
        @cancel="handleDetailCancel"
      />
    </a-modal>
  </div>
</template>

<script setup>
import {
  computed,
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  h,
  shallowRef,
} from "vue";
import {
  Message,
  Modal,
  Tag as ATag,
  Button as AButton,
  Popconfirm as APopconfirm,
} from "@arco-design/web-vue";
import { defineAsyncComponent } from "vue";
import { useRouter } from "vue-router";
import {
  getPagePurchaseApplicationListApi,
  deletePurchaseApplicationByPurchaseApplicationIdApi,
} from "~/api/lindi/purchaseApplication.js";

// 动态导入组件
const PurchaseApplicationEditPage = defineAsyncComponent(() =>
  import("./PurchaseApplicationEdit.vue")
);
const PurchaseApplicationProcess = defineAsyncComponent(() =>
  import("./PurchaseApplicationProcess.vue")
);
const PurchaseApplicationDetail = defineAsyncComponent(() =>
  import("./PurchaseApplicationDetail.vue")
);

// 全局实例
const { proxy } = getCurrentInstance();
const router = useRouter();

// 字典数据
const dicts = proxy.LoadDicts([
  proxy.DICT.lindiProjectType,
  proxy.DICT.lindiPurchaseApplicationStatus,
]);

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);
const deleteLoading = ref(false);

// 搜索行显示状态
const showSearchRow = ref(true);

// 查询表单
const searchForm = reactive({
  purchaseApplicationCode: "",
  purchaseApplicationName: "",
  purchaseApplicationStatus: null,
  applicationTimeRange: null,
});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  purchaseApplicationCode: "",
  purchaseApplicationName: "",
  purchaseApplicationStatus: null,
  applicationTimeStart: null,
  applicationTimeEnd: null,
});

// 分页信息
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 表格数据
const tableData = ref([]);

// 表格列
const columns = [
  {
    title: "申请编号",
    dataIndex: "purchaseApplicationCode",
    key: "purchaseApplicationCode",
    width: 150,
    ellipsis: true,
    tooltip: true,
    render: ({ record }) => {
      return h(
        "a",
        {
          style: { color: "#165dff", cursor: "pointer" },
          onClick: () => handleDetail(record),
        },
        record.purchaseApplicationCode
      );
    },
  },
  {
    title: "申请名称",
    dataIndex: "purchaseApplicationName",
    key: "purchaseApplicationName",
    width: 200,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "申请状态",
    dataIndex: "purchaseApplicationStatus",
    key: "purchaseApplicationStatus",
    width: 120,
    align: "center",
    render: ({ record }) => {
      const statusText = getStatusText(record.purchaseApplicationStatus);
      const statusColor = getStatusColor(record.purchaseApplicationStatus);
      return h(ATag, { color: statusColor }, () => statusText);
    },
  },
  {
    title: "申请时间",
    dataIndex: "applicationTime",
    key: "applicationTime",
    width: 180,
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    width: 180,
    align: "center",
    fixed: "right",
    render: ({ record }) => {
      return h("div", { class: "action-buttons" }, [
        h(
          AButton,
          {
            type: "text",
            size: "small",
            onClick: () => handleEdit(record),
            "v-perm": ["lindi:purchaseApplication:update"],
          },
          () => "编辑"
        ),
        h(
          AButton,
          {
            type: "text",
            size: "small",
            onClick: () => handleProcess(record),
            "v-perm": ["lindi:purchaseApplication:approve"],
          },
          () => "处理"
        ),
        h(
          APopconfirm,
          {
            content: `确认要删除申请编号为"${record.purchaseApplicationCode}"，申请名称为"${record.purchaseApplicationName}"的购买申请吗？`,
            onOk: () => handleDeleteConfirm(record.purchaseApplicationId),
          },
          {
            default: () =>
              h(
                AButton,
                {
                  type: "text",
                  size: "small",
                  status: "danger",
                  loading: deleteLoading.value,
                  "v-perm": ["lindi:purchaseApplication:delete"],
                },
                () => "删除"
              ),
          }
        ),
      ]);
    },
  },
];

// 编辑页面显示状态
const showEditPage = ref(false);
const showProcessPage = ref(false);
const showDetailModal = ref(false);
const editParams = ref({});
const processParams = ref({});
const detailParams = ref({});

// 获取状态颜色
const getStatusColor = (status) => {
  if (!status || !dicts[proxy.DICT.lindiPurchaseApplicationStatus]) {
    return "gray";
  }
  console.log("status", status);
  console.log("dicts", dicts[proxy.DICT.lindiPurchaseApplicationStatus]);
  const dict = dicts[proxy.DICT.lindiPurchaseApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict?.dictClass || "gray";
};

// 获取状态文本
const getStatusText = (status) => {
  if (!status || !dicts[proxy.DICT.lindiPurchaseApplicationStatus]) {
    return "未知状态";
  }
  const dict = dicts[proxy.DICT.lindiPurchaseApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict ? dict.dictValue : "未知状态";
};

// 获取项目类型文本
const getProjectTypeText = (type) => {
  if (!type || !dicts[proxy.DICT.lindiProjectType]) {
    return "未知类型";
  }
  const dict = dicts[proxy.DICT.lindiProjectType].find(
    (d) => String(d.dictKey) === String(type)
  );
  return dict ? dict.dictValue : "未知类型";
};

// 格式化日期（年月日）
const formatDate = (dateTime) => {
  if (!dateTime) return "";
  const date = new Date(dateTime);
  return date
    .toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    })
    .replace(/\//g, "-");
};

// 格式化时间（时分秒）
const formatTime = (dateTime) => {
  if (!dateTime) return "";
  const date = new Date(dateTime);
  return date.toLocaleTimeString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 移除模拟数据，使用真实API

// 查询数据列表
const search = () => {
  // 同步searchForm到queryParams
  queryParams.purchaseApplicationCode = searchForm.purchaseApplicationCode;
  queryParams.purchaseApplicationName = searchForm.purchaseApplicationName;
  queryParams.purchaseApplicationStatus = searchForm.purchaseApplicationStatus;

  // 处理时间范围
  if (
    searchForm.applicationTimeRange &&
    searchForm.applicationTimeRange.length === 2
  ) {
    queryParams.applicationTimeStart = searchForm.applicationTimeRange[0];
    queryParams.applicationTimeEnd = searchForm.applicationTimeRange[1];
  } else {
    queryParams.applicationTimeStart = null;
    queryParams.applicationTimeEnd = null;
  }

  loading.value = true;

  getPagePurchaseApplicationListApi({
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    purchaseApplicationCode: queryParams.purchaseApplicationCode,
    purchaseApplicationName: queryParams.purchaseApplicationName,
    purchaseApplicationStatus: queryParams.purchaseApplicationStatus,
    applicationTimeStart: queryParams.applicationTimeStart,
    applicationTimeEnd: queryParams.applicationTimeEnd,
  })
    .then((response) => {
      tableData.value = response.records || [];
      pagination.total = response.total || 0;
      pagination.current = queryParams.pageNum;
      pagination.pageSize = queryParams.pageSize;
    })
    .catch((error) => {
      console.error("查询购买申请列表失败:", error);
      Message.error("查询失败: " + (error.message || "网络错误"));
      tableData.value = [];
      pagination.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 重置查询
const reset = () => {
  // 重置searchForm
  searchForm.purchaseApplicationCode = "";
  searchForm.purchaseApplicationName = "";
  searchForm.purchaseApplicationStatus = null;
  searchForm.applicationTimeRange = null;

  // 重置queryParams
  queryParams.purchaseApplicationCode = "";
  queryParams.purchaseApplicationName = "";
  queryParams.purchaseApplicationStatus = null;
  queryParams.applicationTimeStart = null;
  queryParams.applicationTimeEnd = null;
  queryParams.pageNum = 1;
  search();
};

// 分页变化
const handlePageChange = (page) => {
  queryParams.pageNum = page;
  search();
};

// 每页条数变化
const handlePageSizeChange = (pageSize) => {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  search();
};

// 新增购买申请
const handleAdd = () => {
  editParams.value = {
    mode: "add",
  };
  showEditPage.value = true;
  showProcessPage.value = false;
};

// 编辑购买申请
const handleEdit = (row) => {
  editParams.value = {
    purchaseApplicationId: row.purchaseApplicationId,
    mode: "edit",
  };
  showEditPage.value = true;
  showProcessPage.value = false;
};

// 删除确认
const handleDeleteConfirm = (purchaseApplicationId) => {
  deleteLoading.value = true;
  deletePurchaseApplicationByPurchaseApplicationIdApi(purchaseApplicationId)
    .then((response) => {
      if (response && response.code === 200) {
        Message.success("删除成功");
        search();
      } else {
        Message.error(response?.message || "删除失败");
      }
    })
    .catch((error) => {
      console.error("删除失败:", error);
      Message.error("删除失败: " + (error.message || "网络错误"));
    })
    .finally(() => {
      deleteLoading.value = false;
    });
};

// 处理购买申请
const handleProcess = (row) => {
  console.log("处理审批:", row);
  processParams.value = {
    purchaseApplicationId: row.purchaseApplicationId,
    mode: "process",
  };
  showEditPage.value = false;
  showProcessPage.value = true;
};

// 查看详情
const handleDetail = (row) => {
  console.log("查看详情:", row);
  detailParams.value = {
    purchaseApplicationId: row.purchaseApplicationId,
  };
  showDetailModal.value = true;
};

// 编辑页面取消
const handleEditCancel = () => {
  showEditPage.value = false;
  editParams.value = {};
};

// 编辑页面确认
const handleEditOk = () => {
  showEditPage.value = false;
  editParams.value = {};
  // 刷新列表
  search();
};

// 审批页面取消
const handleProcessCancel = () => {
  showProcessPage.value = false;
  processParams.value = {};
};

// 审批页面确认
const handleProcessOk = () => {
  showProcessPage.value = false;
  processParams.value = {};
  search();
};

// 详情模态窗取消
const handleDetailCancel = () => {
  showDetailModal.value = false;
  detailParams.value = {};
};

// 处理页面刷新
const handleProcessRefresh = () => {
  // 刷新列表
  search();
};

// 初始化
onMounted(() => {
  search();
});
</script>
<style scoped>
.address-cell,
.code-cell {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
  text-align: center;
  max-width: 100%;
  padding: 8px;
}

.time-cell {
  text-align: center;
  line-height: 1.4;
}

.time-detail {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}
</style>
